package com.sjt.blog.web.admin;

import com.sjt.blog.po.Tag;
import com.sjt.blog.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;

@Controller
@RequestMapping("/admin")
public class TagsController {

    @Autowired
    private TagService tagService;

    @GetMapping("/tags")
    public String list(@PageableDefault(size = 10, sort = ("id"), direction = Sort.Direction.DESC) Pageable pageable,
                       Model model){
        model.addAttribute("page", tagService.listTags(pageable));
        return "admin/tags";
    }

    @GetMapping("/tags/input")
    public String tagInput(Model model){
        model.addAttribute("tag", new Tag());
        return "admin/tags-input";
    }

    @PostMapping("/tags")
    public String doInput(@Valid Tag tag, BindingResult result, RedirectAttributes attributes){
        // 不能重复
        Tag tag1 = tagService.getTagByName(tag.getName());
        if (tag1 != null){
            result.rejectValue("name", "nameError", "该标签已存在！");
        }
        // 标签名不能为空！
        if (result.hasErrors()){
            return "admin/tags-input";
        }

        // 判断是新增还是更新
        Tag t;
        if (tag.getId() == null){
            t = tagService.save(tag);
        }else {
            t = tagService.updateTag(tag.getId(), tag);
        }
        // 更新或者新增操作是否成功
        if (t == null){
            // 保存失败
            attributes.addFlashAttribute("message", "操作失败！");
        }else {
            // 保存成功，重定向会列表
            attributes.addFlashAttribute("message", "操作成功！");
        }

        return "redirect:/admin/tags";
    }

    @GetMapping("/tags/{id}/input")
    public String editInput(@PathVariable("id") Long id,Model model){
        model.addAttribute("tag", tagService.getTag(id));
        return "admin/tags-input";
    }

    @GetMapping("/tags/{id}/delete")
    public String deleteTag(@PathVariable("id") Long id, RedirectAttributes attributes){
        tagService.deleteTag(id);
        attributes.addFlashAttribute("message", "删除成功！");
        return "redirect:/admin/tags";
    }

}
